<template>
  <!-- 自定义导航栏 -->
  <CustomNavbar />
  <scroll-view
    refresher-enabled
    :refresher-triggered="isTriggered"
    @refresherrefresh="onRefresherrefresh"
    @scrolltolower="onScrolltolower"
    class="scroll-view"
    scroll-y
  >
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!-- 自定义轮播图 -->
      <XtxSwiper :list="bannerList" />
      <!-- 分类面板 -->
      <CategoryPanel :list="categoryList" />
      <!-- 热门推荐功能 -->
      <HotPanel :list="hotList" />
      <!-- 猜你喜欢 -->
      <XtxGuess v-if="!isTriggered" ref="guessRef" />
    </template>
  </scroll-view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
// 引入头部组件
import CustomNavbar from './components/CustomNavbar.vue'
// 引入首页的业务组件
import CategoryPanel from './components/CategoryPanel.vue'
// 引入热门推荐功能组件
import HotPanel from './components/HotPanel.vue'
// 引入主页骨架屛组件
import PageSkeleton from './components/PageSkeleton.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/api/home'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home.d'
import { useGussetList } from '@/composables'

// 存储主页轮播图的数据
const bannerList = ref<BannerItem[]>([])
// 获取主页轮播图的数据
const getHomeBannerData = async () => {
  const { code, result } = await getHomeBannerAPI()
  if (code == '1') {
    bannerList.value = result
  }
}

// 存储前台分类数据
const categoryList = ref<CategoryItem[]>([])
// 获取前台分类数据
const getHomeCategoryDate = async () => {
  let { code, result } = await getHomeCategoryAPI()
  if (code == '1') {
    categoryList.value = result
  }
}

// 存储热门推荐数据
const hotList = ref<HotItem[]>([])
// 获取热门推荐数据
const getHomeHotDate = async () => {
  let { code, result } = await getHomeHotAPI()
  if (code == '1') {
    hotList.value = result
  }
}

// 猜你喜欢组合式函数
const { guessRef, onScrolltolower } = useGussetList()

// 设置当前下拉刷新状态
const isTriggered = ref(false)
// 自定义下来刷新触发
const onRefresherrefresh = async () => {
  // 开始动画
  isTriggered.value = await true
  // 加载数据
  // await getHomeBannerData()
  // await getHomeCategoryDate()
  // await getHomeHotDate()
  await Promise.all([getHomeBannerData(), getHomeCategoryDate(), getHomeHotDate()])
  // 关闭动画
  isTriggered.value = await false
}

const isLoading = ref(false)
// 页面加载
onLoad(async () => {
  isLoading.value = await true
  await Promise.all([getHomeBannerData(), getHomeCategoryDate(), getHomeHotDate()])
  isLoading.value = await false
})
</script>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.scroll-view {
  flex: 1;
}
</style>
